<?php

namespace app\data\controller\api;

use app\data\service\CommentService;
use app\data\service\GoodsService;
use app\data\service\UserAdminService;
use think\admin\Controller;

/**
 * 商品评价数据接口
 * Class Goods
 * @package app\data\controller\api
 */
class Comment extends Controller
{
    /**
     * 获取评价列表
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getComments()
    {
        $query = $this->_query('ShopGoodsComments')->equal('goods_code');
        $uuid = input('uuid');
        if ($uuid) {
            $result = $query->where(function ($query) use ($uuid) {
                return $query->where(['deleted' => 0, 'status' => 1])->whereOr('uuid', $uuid);
            })->order('id desc')->page(true, false, false, input('limit', 10));
        } else {
            $result = $query->where(['deleted' => 0, 'status' => 1])->order('id desc')->page(true, false, false, input('limit', 10));
        }

        CommentService::instance()->bindData($result['list']);
        $this->success('获取商品数据', $result);
    }

    /**
     * 商品星级评分
     */
    public function goodsStar()
    {
        $map = $this->_vali([
            'goods_code.require' => '商品Code不能为空！'
        ]);
        $query = $this->app->db->name('ShopGoodsComments')->where($map)->where(['deleted' => 0, 'status' => 1]);

        $count = $query->count();


        if ($count > 0) {
            $star = $query->where(['deleted' => 0, 'status' => 1])->avg('star');
            $favorableCount = $query->where('star', '>=', 3)->count();
            $favorableRate = bcdiv($favorableCount, $count, 0) . '%';
        } else {
            $star = 5;
            $favorableRate = '100%';
        }

        $this->success('获取商品星级评分', [
            'star' => $star,
            'favorable_rate' => $favorableRate
        ]);
    }
}